﻿#region Using directives

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using MCMLXVII.BackEnd.Services.SystemConfiguration.Messages;
using MCMLXVII.BackEnd.Services.Common.Messages;
using MCMLXVII.BackEnd.Services.OrganizationChart.Interfaces;
using MCMLXVII.BackEnd.Services.OrganizationChart.Messages;
using MCMLXVII.Tools.OrganizationChart.SmartEditors;
using System.ServiceModel;

#endregion

namespace MCMLXVII.Tools.OrganizationChart
{
    partial class frmMain : Form
    {
        private Hashtable _NodeCache = new Hashtable();
        private int _NodeInBrowserList = 0;
        private string[] _Permissions;

        private const string CP_ManageObjects = "OrganizationChart.ManageObjects";
        private const string CP_ViewAudit = "OrganizationChart.ViewAudit";
        private const string CP_ManageSecurity = "OrganizationChart.ManageSecurity";

        #region initialization
        public frmMain()
        {
            InitializeComponent();
            LoadClassesAndInitMenus();
            MembersClasses.MemberBase.InitDefualtLanguage();
            OrganizationTree.BeginUpdate();
            LoadOrganizationTree(1);
            OrganizationTree.EndUpdate();
            _Permissions = BusinessActions.GetPermissions();
        }
        private void LoadClassesAndInitMenus()
        {
            ToolStripMenuItem[] tsiList;
            OrganizationMembersClassesManager.LoadOrganizationTreeMembersClasses();
            int i = 0;
            tsiList = new ToolStripMenuItem[OrganizationMembersClassesManager.OrganizationTreeMemberClasses.Length];
            foreach (iOrganizationTreeMemberClass x in OrganizationMembersClassesManager.OrganizationTreeMemberClasses)
            {
                //load icons into the imagelist for listview support
                imlMembersClasses.Images.Add("img" + x.MemberClass.ToString(), x.GetIcon());

                //Complete the new drop down command button
                tsiList[i] = new ToolStripMenuItem();
                tsiList[i].Text = x.MemberClassDescription;
                tsiList[i].Image = x.GetIcon().ToBitmap();
                tsiList[i].Visible = true;
                tsiList[i].Available = true;
                tsiList[i].Click += new EventHandler(NewNodeMember_Click);
                i++;
            }
            ctxnewToolStripMenuItem.DropDownItems.AddRange(tsiList);
            ctxreloadToolStripMenuItem.Click += new EventHandler(toolStripReload_Click);
            ctxauditToolStripMenuItem.Click += new EventHandler(toolStripAuditCtx_Click);
            ctxdeleteToolStripMenuItem.Click += new EventHandler(toolStripDeleteCtx_Click);
            ctxexitToolStripMenuItem.Click += new EventHandler(toolStripExit_Click);
            ctxmoveToolStripMenuItem.Click += new EventHandler(toolStripMoveCtx_Click);
            ctxsecurityToolStripMenuItem.Click += new EventHandler(toolStripSecurityCtx_Click);

            ctxMemberAudit.Click += new EventHandler(toolStripAudit_Click);
            ctxMemberMove.Click += new EventHandler(toolStripMove_Click);
            ctxMemberDelete.Click += new EventHandler(toolStripDelete_Click);
            ctxMemberSecurity.Click += new EventHandler(toolStripSecurity_Click);

            ucEncabezado1.ExitRequested += new EventHandler(toolStripExit_Click);
            ucEncabezado1.ReloadRequested += new EventHandler(toolStripReload_Click);
        }

        private void LoadOrganizationTree(int SelectNodeID)
        {
            msgOrganizationNodeInfo root = BusinessActions.GetOrganizationTree();
            TreeNode tn = new TreeNode(root.Name, 0, 0);
            tn.Tag = root.NodeID.ToString();
            OrganizationTree.Nodes.Add(tn);
            _NodeCache.Add(root.NodeID, new OrganizationTreeNode(root, tn.Index));
            if (root.NodeID == SelectNodeID)
            {
                tn.Expand();
                OrganizationTree.SelectedNode = tn;

            }
            CompleteNodes(tn, root.FirstChild, SelectNodeID);
        }

        private void CompleteNodes(TreeNode tn, msgOrganizationNodeInfo root, int SelectnodeID)
        {
            if (root != null)
            {
                TreeNode tch = new TreeNode(root.Name, 1, 2);
                tch.Tag = root.NodeID.ToString();
                tn.Nodes.Add(tch);
                _NodeCache.Add(root.NodeID, new OrganizationTreeNode(root, tch.Index));
                if (root.NodeID == SelectnodeID)
                {
                    tch.Expand();
                    OrganizationTree.SelectedNode = tch;
                }
                CompleteNodes(tch, root.FirstChild, SelectnodeID);

                while (root.NextBrother != null)
                {
                    TreeNode tcx = new TreeNode(root.NextBrother.Name, 1, 2);
                    tcx.Tag = root.NextBrother.NodeID.ToString();
                    tn.Nodes.Add(tcx);
                    _NodeCache.Add(root.NextBrother.NodeID, new OrganizationTreeNode(root.NextBrother, tcx.Index));
                    CompleteNodes(tcx, root.NextBrother.FirstChild, SelectnodeID);
                    if (root.NextBrother.NodeID == SelectnodeID)
                    {
                        tcx.Expand();
                        OrganizationTree.SelectedNode = tcx;
                    }
                    root = root.NextBrother;
                }
            }
        }

        #endregion

        #region Functions


        private void UpdateOrganizationTreeNodeText(int SelectNodeID, string NodeText)
        {

            foreach (TreeNode tn in OrganizationTree.Nodes)
            {
                if (tn.Tag.ToString() == SelectNodeID.ToString())
                {
                    tn.Text = NodeText;
                    break;
                }
                if (tn.Nodes.Count > 0)
                {
                    if (bUpdateOrganizationTreeNodeText(tn.Nodes, SelectNodeID, NodeText))
                        break;
                }
            }
        }

        private bool bUpdateOrganizationTreeNodeText(TreeNodeCollection TreeCol, int SelectNodeID, string NodeText)
        {
            foreach (TreeNode tn in TreeCol)
            {
                if (tn.Tag.ToString() == SelectNodeID.ToString())
                {
                    tn.Text = NodeText;
                    return true;
                }
                else
                {
                    if (tn.Nodes.Count > 0)
                    {
                        bool b = bUpdateOrganizationTreeNodeText(tn.Nodes, SelectNodeID, NodeText);
                        if (b) 
                            return true;
                    }
                }
            }
            return false;
        }

        private int MemberPosInListView(int MemberID)
        {
            foreach (ListViewItem lv in NodeMembersList.Items)
            {
                string MemberLine = lv.Text;
                int i, j;
                i = MemberLine.LastIndexOf('(');
                j = MemberLine.LastIndexOf(')');
                if ((j > i) && (i > 0))
                {
                    if (MemberID == Convert.ToInt32(MemberLine.Substring(i + 1, j - i - 1)))
                    {
                        return lv.Index;
                    }
                }

            }
            return -1;
        }

        private bool MustEventProceed(out int NodeID, out int MemberID, out bool IsNode, bool ToolbarClicked)
        {
            MemberID = 0;
            NodeID = 0;
            IsNode = false;

            if (ToolbarClicked)
            {
                if (tabControl1.SelectedIndex == 0)
                {
                    // Browse Tab, the curren node is selected
                    if (NodeMembersList.SelectedItems.Count == 1)
                    {
                        string MemberLine = NodeMembersList.SelectedItems[0].Text;
                        int i, j;
                        i = MemberLine.LastIndexOf('(');
                        j = MemberLine.LastIndexOf(')');
                        if ((j > i) && (i > 0))
                        {
                            MemberID = Convert.ToInt32(MemberLine.Substring(i + 1, j - i - 1));
                            NodeID = _NodeInBrowserList;
                            IsNode = false;
                            return true;
                        }
                        else
                            return false;
                    }
                    else
                    {
                        NodeID = _NodeInBrowserList;
                        IsNode = true;
                        return true;
                    }
                }
                else
                {
                    string tag = tabControl1.SelectedTab.Tag.ToString();
                    IsNode = (tag.Substring(0, 1) == "N");
                    int ID = Int32.Parse(tag.Substring(2));
                    if (!IsNode)
                    {
                        NodeID = ((ucSmartBaseEditor)tabControl1.SelectedTab.Controls[0]).NodeID;
                        MemberID = ID;
                        IsNode = false;
                        return true;
                    }
                    else
                    {
                        NodeID = ID;
                        IsNode = true;
                        return true;
                    }
                }
            }
            else
            {
                if (OrganizationTree.SelectedNode != null)
                {
                    //Curren tree node is selected
                    NodeID = Int32.Parse(OrganizationTree.SelectedNode.Tag.ToString());
                    IsNode = true;
                    return true;
                }
                else
                    return false;
            }
        }

        private void CreateTab(NodeEditorHelper node)
        {
            string TabKey = "Item:" + node.ID.ToString();
            ucSmartBaseEditor uc = node.GetEditControl(ucEncabezado1.EditInGrid);
            tabControl1.TabPages.Add(TabKey, ":" + node.Name);
            tabControl1.TabPages[TabKey].Controls.Add(uc);
            tabControl1.TabPages[TabKey].Tag = "N:" + node.ID.ToString();
            uc.Dock = DockStyle.Fill;
            uc.EditorClosed += new EventHandler<MemberUpdatedEventsArgs>(this.EditorTab_Closed);
            uc.MemberUpdated += new EventHandler<MemberUpdatedEventsArgs>(this.EditorTab_Saved);
            tabControl1.SelectTab(TabKey);
        }

        private void CreateTab(MembersClasses.MemberBase member)
        {
            string TabKey = "Item:" + member.MemberID.ToString();
            ucSmartBaseEditor uc = member.GetEditor(ucEncabezado1.EditInGrid);
            tabControl1.TabPages.Add(TabKey, ":" + member.Description);
            tabControl1.TabPages[TabKey].Controls.Add(uc);
            tabControl1.TabPages[TabKey].Tag = "M:" + member.MemberID.ToString();
            uc.Dock = DockStyle.Fill;
            uc.EditorClosed += new EventHandler<MemberUpdatedEventsArgs>(this.EditorTab_Closed);
            uc.MemberUpdated += new EventHandler<MemberUpdatedEventsArgs>(this.EditorTab_Saved);
            tabControl1.SelectTab(TabKey);
        }

        private bool InitializeNodePermissions(OrganizationTreeNode Node)
        {
            string[] Permissions;
            if (!Node.ArePermissionsInitialized())
            {
                Permissions = BusinessActions.GetOrganizationTreeNodeEfectiveRights(Node.BaseOrganizationNodeInfo.NodeID);
                Node.Permissions = Permissions;
            }
            else
            {
                Permissions = Node.Permissions;
            }
            return UpdateToolbar(Permissions);
        }

        private bool UpdateToolbar(string[] Permissions)
        {
            string xPer = "_";
            foreach (string x in Permissions)
            {
                xPer += x;
            }
            ctxMemberAudit.Enabled = (xPer.IndexOf('A') > 0) && (Array.Exists<string>(_Permissions, IsViewAuditAllowed));
            ctxauditToolStripMenuItem.Enabled = (xPer.IndexOf('A') > 0) && (Array.Exists<string>(_Permissions, IsViewAuditAllowed));
            ctxMemberSecurity.Enabled = (xPer.IndexOf('S') > 0) && (Array.Exists<string>(_Permissions, IsManageSecurityAllowed));
            ctxsecurityToolStripMenuItem.Enabled = (xPer.IndexOf('S') > 0) && (Array.Exists<string>(_Permissions, IsManageSecurityAllowed));

            ctxMemberDelete.Enabled = (xPer.IndexOf('F') > 0 || xPer.IndexOf('D') > 0) && (Array.Exists<string>(_Permissions, IsManageObjectAllowed));
            ctxdeleteToolStripMenuItem.Enabled = (xPer.IndexOf('F') > 0 || xPer.IndexOf('D') > 0) && (Array.Exists<string>(_Permissions, IsManageObjectAllowed));
            ctxMemberMove.Enabled = (xPer.IndexOf('F') > 0 || xPer.IndexOf('U') > 0) && (Array.Exists<string>(_Permissions, IsManageObjectAllowed));
            ctxmoveToolStripMenuItem.Enabled = (xPer.IndexOf('F') > 0 || xPer.IndexOf('U') > 0) && (Array.Exists<string>(_Permissions, IsManageObjectAllowed));
            ctxnewToolStripMenuItem.Enabled = (xPer.IndexOf('F') > 0 || xPer.IndexOf('C') > 0) && (Array.Exists<string>(_Permissions, IsManageObjectAllowed));

            return (xPer.IndexOf('F') > 0 || xPer.IndexOf('U') > 0) && (Array.Exists<string>(_Permissions, IsManageObjectAllowed));
        }


        private bool IsManageObjectAllowed(string per)
        {
            return (per == CP_ManageObjects);
        }

        private bool IsViewAuditAllowed(string per)
        {
            return (per == CP_ViewAudit);
        }
        private bool IsManageSecurityAllowed(string per)
        {
            return (per == CP_ManageSecurity);
        }

        #endregion

        #region OrganizationTree Event Handlers

        private void OrganizationTree_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (!e.Node.IsSelected)
            {
                OrganizationTree.SelectedNode = e.Node;
            }
        }


        private void OrganizationTree_DoubleClick(object sender, EventArgs e)
        {

            if (OrganizationTree.SelectedNode != null)
            {
                string TabKey = "Item:" + OrganizationTree.SelectedNode.Tag.ToString();
                if (!tabControl1.TabPages.ContainsKey(TabKey))
                {
                    int nodeid = Int32.Parse(OrganizationTree.SelectedNode.Tag.ToString());
                    OrganizationTreeNode Node = (OrganizationTreeNode)_NodeCache[nodeid];
                    bool EditEnabled;
                    if (!Node.ArePermissionsInitialized())
                        EditEnabled = InitializeNodePermissions(Node);
                    else
                        EditEnabled = UpdateToolbar(Node.Permissions);
                    CreateTab(new NodeEditorHelper(Node));
                }
                tabControl1.SelectTab(TabKey);
            }
        }

        private void OrganizationTree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            OrganizationTreeNode Node = (OrganizationTreeNode)_NodeCache[Int32.Parse(e.Node.Tag.ToString())];
            bool EditEnabled;
            if (!Node.ArePermissionsInitialized())
                EditEnabled = InitializeNodePermissions(Node);
            else
                EditEnabled = UpdateToolbar(Node.Permissions);
            if (!Node.AreMembersInitialized())
            {
                Node.Members = BusinessActions.GetOrganizationTreeNodeMembers(Node.BaseOrganizationNodeInfo.NodeID);
            }
            LoadMembersList(Node);
            int nodeid = Int32.Parse(e.Node.Tag.ToString());
            _NodeInBrowserList = nodeid;
            string key = "Item:" + nodeid.ToString();
            if (tabControl1.TabPages.ContainsKey(key))
                tabControl1.SelectTab(key);
            else
                tabControl1.SelectTab(0);
        }

        #endregion

        #region TabsManagenent
        private void EditorTab_Closed(object sender, MemberUpdatedEventsArgs e)
        {
            string key = "Item:" + e.MemberID.ToString();
            if (tabControl1.TabPages.ContainsKey(key))
                tabControl1.TabPages.RemoveByKey(key);
        }


        private void EditorTab_Saved(object sender, MemberUpdatedEventsArgs e)
        {
            string key = "Item:" + e.MemberID.ToString();
            if (e.IsNode)
            {
                OrganizationTreeNode node = (OrganizationTreeNode)_NodeCache[e.NodeInfo.ID];
                node.LoadEditorInfo(e.NodeInfo);
                msgUpdateOrganizationTreeNode req = new msgUpdateOrganizationTreeNode(node.BaseOrganizationNodeInfo.NodeID, node.BaseOrganizationNodeInfo.Name, node.BaseOrganizationNodeInfo.FatherID, node.BaseOrganizationNodeInfo.DirectoryConfigInfo, node.BaseOrganizationNodeInfo.UpdateSequence);
                req.Translations = node.BaseOrganizationNodeInfo.Translations;
                try
                {
                    node.BaseOrganizationNodeInfo.UpdateSequence = BusinessActions.UpdateOrganizationTreeNode(req);
                    key = "Item:" + node.BaseOrganizationNodeInfo.NodeID.ToString();
                    tabControl1.TabPages[key].Text = ":" + e.NodeInfo.Name;
                    UpdateOrganizationTreeNodeText(e.NodeInfo.ID, e.NodeInfo.Name);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                if (e.MemberInfo.HasChanges())
                {
                    msgUpdateOrganizationMember req = new msgUpdateOrganizationMember(e.MemberInfo.GetMemberData());
                    try
                    {
                        e.MemberInfo.UpdateSequence = BusinessActions.UpdateOrganizationMember(req);
                        ((OrganizationTreeNode)_NodeCache[e.FatherNodeID]).UpdateMember(e.MemberInfo.MemberID, e.MemberInfo.Description);
                        if (_NodeInBrowserList == e.FatherNodeID)
                        {
                            int i = MemberPosInListView(e.MemberInfo.MemberID);
                            if (i > -1)
                                NodeMembersList.Items[i].Text = e.MemberInfo.Description + " (" + e.MemberID.ToString() + ")";
                        }                                               
                        if (tabControl1.TabPages.ContainsKey(key))
                            tabControl1.TabPages[key].Text = ":"+e.MemberInfo.Description;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }

        }
        #endregion

        #region MembersLists

        private void LoadMembersList(OrganizationTreeNode Node)
        {
            NodeMembersList.Clear();
            if (Node.AreMembersInitialized())
            {
                foreach (msgOrganizationTreeNodeMember Member in Node.Members)
                {
                    NodeMembersList.Items.Add(Member.Description + " (" + Member.MemberID.ToString() + ")", "img" + Member.MemberClass.ToString());
                }
            }
        }

        private void NodeMembersList_DoubleClick(object sender, EventArgs e)
        {
            if (((ListView)sender).SelectedItems.Count == 1)
            {
                //Get the editing object ID and Load Object Information
                int MemberID = 0;
                string MemberLine = ((ListView)sender).SelectedItems[0].Text;
                int i, j;
                i = MemberLine.LastIndexOf('(');
                j = MemberLine.LastIndexOf(')');
                if ((j > i) && (i > 0))
                {
                    MemberID = Convert.ToInt32(MemberLine.Substring(i + 1, j - i - 1));
                    string key = "Item:" + MemberID.ToString();
                    if (!tabControl1.TabPages.ContainsKey(key))
                    {
                        msgSimpleMemberRequest req = new msgSimpleMemberRequest(_NodeInBrowserList, MemberID);
                        msgOrganizationMemberInfo inf = BusinessActions.GetOrganizationMemberInfo(req);
                        CreateTab((MembersClasses.MemberBase)OrganizationMembersClassesManager.GetOrganizationTreeMemberEditor(inf));
                    }
                    tabControl1.SelectTab(key);
                }
            }
        }

        #endregion

        #region MenuClicks event handlers

        private void toolStripExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }


        private void toolStripReload_Click(object sender, EventArgs e)
        {
            _NodeCache.Clear();
            _NodeInBrowserList = 0;
            NodeMembersList.Items.Clear();
            for (int i = tabControl1.TabPages.Count - 1; i > 0; i--)
            {
                tabControl1.TabPages.RemoveAt(i);
            }
            OrganizationTree.Nodes.Clear();
            OrganizationTree.BeginUpdate();
            LoadOrganizationTree(1);
            OrganizationTree.EndUpdate();
        }
        #endregion

        #region Crete Node and Members

        public void NewNodeMember_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem senderButton = (ToolStripMenuItem)sender;
            Nullable<int> NewClassID = OrganizationMembersClassesManager.GetOrganizationMemberClassIDByName(senderButton.Text);
            if (NewClassID != null)
            {
                if (OrganizationTree.SelectedNode != null)
                {
                    OrganizationTreeNode EditingNodeObject = ((OrganizationTreeNode)_NodeCache[Int32.Parse(OrganizationTree.SelectedNode.Tag.ToString())]);
                    int FatherNodeID = EditingNodeObject.BaseOrganizationNodeInfo.NodeID;
                    int EditingObjectClass = NewClassID.Value;
                    iOrganizationTreeMemberClass EditingObject = OrganizationMembersClassesManager.GetOrganizationTreeMemberEditor(FatherNodeID, senderButton.Text, NewClassID.Value);
                    EditingNodeObject.AddMember(new msgOrganizationTreeNodeMember(EditingObject.MemberID, EditingObject.Description, NewClassID.Value));

                    NodeMembersList.SelectedItems.Clear();
                    ListViewItem lv = NodeMembersList.Items.Add(EditingObject.Description + " (" + EditingObject.MemberID.ToString() + ")", "img" + EditingObject.MemberClass.ToString());
                    CreateTab((MembersClasses.MemberBase)EditingObject);
                    lv.Selected = true;
                }
            }

        }

        private void toolStripNewNodeFolder_Click(object sender, EventArgs e)
        {
            if (OrganizationTree.SelectedNode != null)
            {
                OrganizationTreeNode Node = (OrganizationTreeNode)_NodeCache[Int32.Parse(OrganizationTree.SelectedNode.Tag.ToString())];
                msgOrganizationNodeInfo TempNode = OrganizationNodesManager.CreateNewNode(Node.BaseOrganizationNodeInfo.NodeID);
                if (TempNode != null)
                {
                    TreeNode tn = new TreeNode(TempNode.Name, 1, 2);
                    tn.Tag = TempNode.NodeID.ToString();
                    int idx = OrganizationTree.SelectedNode.Nodes.Add(tn);
                    OrganizationTreeNode TempONode = new OrganizationTreeNode(TempNode, idx);
                    _NodeCache.Add(TempNode.NodeID, TempONode);
                    TempONode.ClearMembers();
                    OrganizationTree.SelectedNode = tn;
                    NodeMembersList.Clear();
                    _NodeInBrowserList = TempNode.NodeID;

                    CreateTab(new NodeEditorHelper(TempONode));
                }
            }
        }
        #endregion

        #region Auditing
        private void toolStripAudit_Click(object sender, EventArgs e)
        {
            int MemberID = 0;
            int NodeID = 0;
            bool IsNode = false;
            if (MustEventProceed(out NodeID, out MemberID, out IsNode, true))
                if (IsNode)
                {
                    if (tabControl1.SelectedIndex > 0)
                        DoNodeAudit(NodeID);
                }
                else
                    DoMemberAudit(NodeID, MemberID);
        }

        private void toolStripAuditCtx_Click(object sender, EventArgs e)
        {
            int MemberID = 0;
            int NodeID = 0;
            bool IsNode = false;
            if (MustEventProceed(out NodeID, out MemberID, out IsNode, false))
                if (IsNode)
                    DoNodeAudit(NodeID);
                else
                    DoMemberAudit(NodeID, MemberID);
        }

        private void DoMemberAudit(int NodeID, int MemberID)
        {
            frmMemberAuditDetail  frm = new frmMemberAuditDetail(NodeID, MemberID);
            frm.ShowDialog(Program.frm);
        }

        private void DoNodeAudit(int NodeId)
        {
            frmAuditDetail frm = new frmAuditDetail(NodeId);
            frm.ShowDialog(Program.frm);
        }

        #endregion

        #region Delete
        private void toolStripDeleteCtx_Click(object sender, EventArgs e)
        {
            int MemberID = 0;
            int NodeID = 0;
            bool IsNode = false;
            if (MustEventProceed(out NodeID, out MemberID, out IsNode, false))
                if (IsNode)
                    DoNodeDelete(NodeID);
                else
                    DoMemberDelete(NodeID, MemberID);
        }

        private void toolStripDelete_Click(object sender, EventArgs e)
        {
            int MemberID = 0;
            int NodeID = 0;
            bool IsNode = false;
            if (MustEventProceed(out NodeID, out MemberID, out IsNode, true))
                if (IsNode)
                {
                 if (tabControl1.SelectedIndex > 0)
                    DoNodeDelete(NodeID);
                }
                else
                    DoMemberDelete(NodeID, MemberID);
        }


        private void DoNodeDelete(int NodeID)
        {
            try
            {
                if (BusinessActions.DeleteOrganizationTreeNode(NodeID))
                {
                    TreeNode t = OrganizationTree.SelectedNode.Parent;
                    OrganizationTree.SelectedNode.Remove();
                    OrganizationTree.SelectedNode = t;
                    if (tabControl1.TabPages.ContainsKey(NodeID.ToString()))
                        tabControl1.TabPages.RemoveByKey(NodeID.ToString());
                    if (_NodeCache.ContainsKey(NodeID))
                        _NodeCache.Remove(NodeID);
                }
            }
            catch (FaultException<BackendFault> fault)
            {
                switch (fault.Detail.faultType)
                {
                    case BackendFaulType.Security: MessageBox.Show(string.Format(Properties.Resources.Exception, fault.Detail.faultDescription ));
                        break;
                    case BackendFaulType.DataUpdateSequence: MessageBox.Show(Properties.Resources.ErrorInUpdateSequence + " " + fault.Detail.faultDescription );
                        break;
                    case BackendFaulType.Functional:  MessageBox.Show(Properties.Resources.Exception + " " + fault.Detail.faultDescription );
                        break;
                    case BackendFaulType.Technical:  MessageBox.Show(Properties.Resources.Exception + " " + fault.Detail.faultDescription );
                        break;                
                }
                
            }
            catch (Exception ex)
            {                
                MessageBox.Show(string.Format(Properties.Resources.Exception, ex.Message));
            }
        }

        private void DoMemberDelete(int NodeID, int MemberID)
        {
            msgSimpleMemberRequest req = new msgSimpleMemberRequest(NodeID, MemberID);
            try
            {
                if (BusinessActions.DeleteOrganizationMember(req))
                {
                    if (_NodeInBrowserList == NodeID)
                    {
                        int idx = MemberPosInListView(MemberID);
                        if (idx > -1)
                            NodeMembersList.Items.RemoveAt(idx);
                    }
                    ((OrganizationTreeNode)_NodeCache[NodeID]).RemoveMember(req.MemberID);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        #endregion

        #region Move node and member
        private void toolStripMoveCtx_Click(object sender, EventArgs e)
        {
            int MemberID = 0;
            int NodeID = 0;
            bool IsNode = false;
            if (MustEventProceed(out NodeID, out MemberID, out IsNode, false))
                if (IsNode)
                    DoMoveNode(NodeID);
                else
                    DoMoveMember(NodeID, MemberID);

        }
        private void toolStripMove_Click(object sender, EventArgs e)
        {
            int MemberID = 0;
            int NodeID = 0;
            bool IsNode = false;
            if (MustEventProceed(out NodeID, out MemberID, out IsNode, true))
                if (IsNode)
                {
                    if (tabControl1.SelectedIndex > 0)
                        DoMoveNode(NodeID);
                }
                else
                    DoMoveMember(NodeID, MemberID);

        }

        private void DoMoveMember(int NodeID, int MemberID)
        {
            frmMoveDestination frmDialog = new frmMoveDestination();
            frmDialog.SourceNode = NodeID;
            System.Windows.Forms.DialogResult res = frmDialog.ShowDialog(); // (Program.frm);
            if (res == System.Windows.Forms.DialogResult.OK)
            {
                int DestNode = frmDialog.SelectedNode;
                OrganizationTreeNode node = (OrganizationTreeNode)_NodeCache[NodeID];
                msgMoveMemberRequest req = new msgMoveMemberRequest(NodeID, MemberID, DestNode, node.BaseOrganizationNodeInfo.UpdateSequence);
                try
                {
                    BusinessActions.MoveOrganizationMember(req);
                    node.RemoveMember(MemberID);
                    int idx = -1;
                    if (_NodeInBrowserList == NodeID)
                    {
                        idx = MemberPosInListView(MemberID);
                        if (idx > -1)
                            NodeMembersList.Items.RemoveAt(idx);
                    }
                    node = (OrganizationTreeNode)_NodeCache[DestNode];
                    node.ReInitMembers();
                    if (_NodeInBrowserList == DestNode)
                    {
                        LoadMembersList(node);
                    }
                    if (tabControl1.TabPages.ContainsKey(MemberID.ToString()))
                        tabControl1.TabPages.RemoveByKey(MemberID.ToString());
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void DoMoveNode(int NodeID)
        {
            frmMoveDestination frmDialog = new frmMoveDestination();
            frmDialog.SourceNode = NodeID;
            System.Windows.Forms.DialogResult res = frmDialog.ShowDialog(Program.frm);
            if (res == System.Windows.Forms.DialogResult.OK)
            {
                int DestNode = frmDialog.SelectedNode;
                OrganizationTreeNode node = (OrganizationTreeNode)_NodeCache[NodeID];
                msgMoveNodeRequest req = new msgMoveNodeRequest(NodeID, DestNode, node.BaseOrganizationNodeInfo.UpdateSequence);
                try
                {
                    node.BaseOrganizationNodeInfo.UpdateSequence = BusinessActions.MoveOrganizationTreeNode(req);
                    _NodeCache.Clear();
                    OrganizationTree.Nodes.Clear();
                    LoadOrganizationTree(req.NodeID);
                }
                catch (FaultException<BackendFault> fault)
                {
                    switch (fault.Detail.faultType)
                    {
                        case BackendFaulType.Security: MessageBox.Show(string.Format(Properties.Resources.Exception, fault.Detail.faultDescription ));
                            break;
                        case BackendFaulType.DataUpdateSequence: MessageBox.Show(Properties.Resources.ErrorInUpdateSequence + " " + fault.Detail.faultDescription );
                            break;
                        case BackendFaulType.Functional:  MessageBox.Show(Properties.Resources.Exception + " " + fault.Detail.faultDescription );
                            break;
                        case BackendFaulType.Technical:  MessageBox.Show(Properties.Resources.Exception + " " + fault.Detail.faultDescription );
                            break;                
                    }
                    
                }
                catch (Exception ex)
                {                
                    MessageBox.Show(string.Format(Properties.Resources.Exception, ex.Message));
                }
            }

        }
        #endregion

        #region Manage Security
        private void toolStripSecurityCtx_Click(object sender, EventArgs e)
        {
            int MemberID = 0;
            int NodeID = 0;
            bool IsNode = false;
            if (MustEventProceed(out NodeID, out MemberID, out IsNode, false))
                if (IsNode)
                    DoNodeSecurity(NodeID);
        }

        private void toolStripSecurity_Click(object sender, EventArgs e)
        {
            int MemberID = 0;
            int NodeID = 0;
            bool IsNode = false;
            if (MustEventProceed(out NodeID, out MemberID, out IsNode, true))
                if (IsNode)
                   if (tabControl1.SelectedIndex > 0)
                     DoNodeSecurity(NodeID);
        }

        private void DoNodeSecurity(int NodeID)
        {
            OrganizationTreeNode node = (OrganizationTreeNode)_NodeCache[NodeID];
            frmURights frm = new frmURights(node.BaseOrganizationNodeInfo.Name, NodeID, false, node.BaseOrganizationNodeInfo.UpdateSequence);
            frm.ShowDialog(Program.frm);
            if (frm.DialogResult == DialogResult.OK)
            {
                try
                {
                    node.BaseOrganizationNodeInfo.BlockInheritance = frm.BlockInheritance;
                    //msgUpdateOrganizationTreeNode upd = new msgUpdateOrganizationTreeNode();                    
                    //node.BaseOrganizationNodeInfo.UpdateSequence= BusinessActions.UpdateOrganizationTreeNode);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }

        }

        #endregion

        private void ctxMemberSecurity_Click(object sender, EventArgs e)
        {
            int MemberID = 0;
            string MemberName = "";
            if (tabControl1.SelectedIndex == 0)
            {
                // Browse Tab, the curren node is selected
                if (NodeMembersList.SelectedItems.Count == 1)
                {
                    string MemberLine = NodeMembersList.SelectedItems[0].Text;
                    int i, j;
                    i = MemberLine.LastIndexOf('(');
                    j = MemberLine.LastIndexOf(')');
                    if ((j > i) && (i > 0))
                    {
                        MemberID = Convert.ToInt32(MemberLine.Substring(i + 1, j - i - 1));
                        MemberName  = MemberLine.Substring(0, i-1);
                    }
                }
            }

            frmUserSecurity frm = new frmUserSecurity(MemberName, MemberID, 0);
            frm.ShowDialog(Program.frm);
        }

        private void ucEncabezado1_Load(object sender, EventArgs e)
        {

        }

   }
}